package tk.mynoteapp.dev.other.eliminateifelse.right.templatemethod;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 模板方法判断
 * 定义一个接口或者抽象类，里面有个support方法判断参数传的code自己是否可以处理，如果可以处理则调用支付逻辑
 */
@Service
public class PayService implements ApplicationContextAware, InitializingBean {

    private ApplicationContext applicationContext;
    private List<IPay> payList = null;

    @Override
    public void afterPropertiesSet() throws Exception {
        if (payList == null) {
            payList = new ArrayList<>();
            Map<String, IPay> beansOfType = applicationContext.getBeansOfType(IPay.class);
            beansOfType.forEach((key, value) -> payList.add(value));
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public void toPay(String code) {
        for (IPay pay : payList) {
            if (pay.support(code)) {
                pay.pay();
            }
        }
    }
}
